const axios = require('axios');
const config = require('../config/baidu');

class BaiduAuth {
  constructor() {
    this.accessToken = null;
    this.tokenExpiry = null;
  }

  async getAccessToken() {
    if (this.accessToken && this.tokenExpiry > Date.now()) {
      return this.accessToken;
    }

    try {
      const response = await axios.post(
        'https://aip.baidubce.com/oauth/2.0/token',
        null,
        {
          params: {
            grant_type: 'client_credentials',
            client_id: config.API_KEY,
            client_secret: config.SECRET_KEY
          }
        }
      );

      this.accessToken = response.data.access_token;
      this.tokenExpiry = Date.now() + (response.data.expires_in * 1000);
      
      return this.accessToken;
    } catch (error) {
      throw new Error(`获取访问令牌失败: ${error.message}`);
    }
  }
}

module.exports = BaiduAuth;